package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"log"
	"mxshop-api/minio-web/service"
	"net/http"
	"path/filepath"
)

type MinioHandler struct {
	svc service.StorageClient
}

func NewMinioHandler(svc service.StorageClient) *MinioHandler {
	return &MinioHandler{svc: svc}
}

func (handler *MinioHandler) RegisterMinioRoutes(server *gin.Engine) {
	//路由分组
	ug := server.Group("/minio")
	ug.POST("/upload", handler.UploadFile)
}

func (handler *MinioHandler) UploadFile(ctx *gin.Context) {
	// 从请求中获取文件和文件头
	file, header, err := ctx.Request.FormFile("file")
	if err != nil {
		log.Printf("Error getting file from request: %v", err)
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to retrieve file"})
		return
	}
	defer file.Close() // 确保文件流被关闭

	// 获取文件的扩展名
	ext := filepath.Ext(header.Filename)
	if ext == "" {
		ext = ".bin" // 默认扩展名，如果没有扩展名
	}

	// 生成UUID作为文件名
	objectName := "uploads/" + uuid.New().String() + ext

	// 获取桶名
	bucketName := "mxshop-api" // 这里可以从请求的参数中获取

	// 上传文件
	urlStr, err := handler.svc.UploadFile(context.Background(), bucketName, objectName, file)
	if err != nil {
		log.Printf("Error uploading file: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to upload file"})
		return
	}

	// 返回文件的 URL
	ctx.JSON(http.StatusOK, gin.H{
		"url": urlStr,
	})
}
